package com.kly.chatter.api.application.task;


import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Maps;
import com.kly.chatter.db.dao.PrivateUnlockConfigDao;
import com.kly.chatter.db.dao.PrivateUnlockRewardDao;
import com.kly.chatter.db.entity.*;
import com.kly.dto.UserPCountDto;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.service.MemberBenefitsService;
import com.kly.user.chatterService.ChatterUserService;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 私密照片、私密视频解锁奖励
 */
@Slf4j
@Component
public class PrivateRewardTask {

    @Autowired
    private PrivateUnlockConfigDao privateUnlockConfigDao;

    @Resource
    private UserService userService;

    @Resource
    private ChatterUserService chatterUserService;

    @Resource
    private MemberBenefitsService memberBenefitsService;

    @Autowired
    private PrivateUnlockRewardDao privateUnlockRewardDao;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

    @Scheduled(fixedDelay = 30000)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            log.info("=============PrivateRewardTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

//        List<PrivateUnlockConfigEntity> privateUnlockConfigEntities = privateUnlockConfigDao.selectAll();
        List<UserInfoDto> chatterList = RpcUtils.getResult(userService.getUserByUserType("1"));
        for (UserInfoDto chatter : chatterList) {
            List<String> modelUserCodes = RpcUtils.getResult(chatterUserService.getModelUserCodes(chatter.getUserCode()));
            for (String modelUserCode : modelUserCodes) {
                LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
                List<UserPCountDto> userPCountDtoList = RpcUtils.getResult(memberBenefitsService.getUserPCount(modelUserCode, chatter.getUserCode(), startTime, endTime));
                for (UserPCountDto userPCountDto : userPCountDtoList) {
                    int type = userPCountDto.getBenefitCode().equals("2") ? 1 : 2;
                    PrivateUnlockRewardEntity privateUnlockRewardEntity = new PrivateUnlockRewardEntity();
                    privateUnlockRewardEntity.setChatterCode(chatter.getUserCode());
                    privateUnlockRewardEntity.setModelCode(modelUserCode);
                    privateUnlockRewardEntity.setUserCode(userPCountDto.getUserCode());
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    Integer rewardDate = Integer.parseInt(userPCountDto.getRewardDate());
                    privateUnlockRewardEntity.setRewardDate(rewardDate);
                    privateUnlockRewardEntity.setType(type);
                    privateUnlockRewardEntity.setUnlockNum(userPCountDto.getPrivateCount());
                    Map<String, Object> params = Maps.newHashMap();
                    params.put("chatterCode", chatter.getUserCode());
                    params.put("modelCode", modelUserCode);
                    params.put("userCode", userPCountDto.getUserCode());
                    params.put("rewardDate", rewardDate);
                    params.put("type", type);
                    List<PrivateUnlockRewardEntity> privateUnlockRewardEntityList = privateUnlockRewardDao.selectByParams(params);
                    if (privateUnlockRewardEntityList.isEmpty()) {
                        privateUnlockRewardDao.insert(privateUnlockRewardEntity);
                    } else if (!Objects.equals(privateUnlockRewardEntity.getUnlockNum(), privateUnlockRewardEntityList.get(0).getUnlockNum())) {
                        privateUnlockRewardEntity.setId(privateUnlockRewardEntityList.get(0).getId());
                        privateUnlockRewardDao.updateByPrimaryKey(privateUnlockRewardEntity);
                    }
                }
            }
        }
    }
    //读取配置信息
    //读取所有的chatter
    //读取所有的model
    //当天时间段内计算奖励
    //插入表

    //分为普通 和奖励

    /**
     * 核对前一天的数据
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(fixedDelay = 30000)
    public void check() {

        if (!taskJobExecutor.contains(localIP)) {
            log.info("=============PrivateRewardTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        List<UserInfoDto> chatterList = RpcUtils.getResult(userService.getUserByUserType("1"));
        for (UserInfoDto chatter : chatterList) {
            List<String> modelUserCodes = RpcUtils.getResult(chatterUserService.getModelUserCodes(chatter.getUserCode()));
            for (String modelUserCode : modelUserCodes) {
                LocalDateTime startTime = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX);
                List<UserPCountDto> userPCountDtoList = RpcUtils.getResult(memberBenefitsService.getUserPCount(modelUserCode, chatter.getUserCode(), startTime, endTime));
                for (UserPCountDto userPCountDto : userPCountDtoList) {
                    int type = userPCountDto.getBenefitCode().equals("2") ? 1 : 2;
                    PrivateUnlockRewardEntity privateUnlockRewardEntity = new PrivateUnlockRewardEntity();
                    privateUnlockRewardEntity.setChatterCode(chatter.getUserCode());
                    privateUnlockRewardEntity.setModelCode(modelUserCode);
                    privateUnlockRewardEntity.setUserCode(userPCountDto.getUserCode());
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    Integer rewardDate = Integer.parseInt(userPCountDto.getRewardDate());
                    privateUnlockRewardEntity.setRewardDate(rewardDate);
                    privateUnlockRewardEntity.setType(type);
                    privateUnlockRewardEntity.setUnlockNum(userPCountDto.getPrivateCount());
                    Map<String, Object> params = Maps.newHashMap();
                    params.put("chatterCode", chatter.getUserCode());
                    params.put("modelCode", modelUserCode);
                    params.put("userCode", userPCountDto.getUserCode());
                    params.put("rewardDate", rewardDate);
                    params.put("type", type);
                    List<PrivateUnlockRewardEntity> privateUnlockRewardEntityList = privateUnlockRewardDao.selectByParams(params);
                    if (privateUnlockRewardEntityList.isEmpty()) {
                        privateUnlockRewardDao.insert(privateUnlockRewardEntity);
                    } else if (!Objects.equals(privateUnlockRewardEntity.getUnlockNum(), privateUnlockRewardEntityList.get(0).getUnlockNum())) {
                        privateUnlockRewardEntity.setId(privateUnlockRewardEntityList.get(0).getId());
                        privateUnlockRewardDao.updateByPrimaryKey(privateUnlockRewardEntity);
                    }
                }
            }
        }
    }
}

